﻿/*
* arkec.corecom.datastruct v1.0.0
*/

(function (window) {

    window.datastruct = {};

    /* 
    -----数据字典(key/value)结构----- 
    */
    datastruct.dictionary = function () {
        var obj = new datastruct.dictionary.fn.init();
        return obj;
    };
    datastruct.dictionary.fn = {

        /* 构造函数 */
        init: function () {

            /* 对象属性 */
            this.count = 0;
            this.arrKeys = new Array();
            this.arrValues = new Array();
            /*-------------------------------*/
        },

        /* 添加或修改元素 */
        setItem: function (key, value) {
            if (!key) {
                return;
            }

            if (!this.containKey(key)) {
                this.arrKeys[this.count] = key;
                this.arrValues[this.count] = value;
                this.count++;
            }
            else {
                var index = this._getElementIndex(key);
                if (index > -1) {
                    this.arrKeys[index] = key;
                    this.arrValues[index] = value;
                }
            }
        },

        /* 删除元素 */
        removeItem: function (key) {
            var index = this._getElementIndex(key);

            if (index > -1) {
                this.arrKeys.splice(index, 1);
                this.arrValues.splice(index, 1);
                this.count--;
            }
        },

        /* 获取元素 */
        getItem: function (key) {
            var kvalue = null;

            var index = this._getElementIndex(key);
            if (index > -1) {
                kvalue = this.arrValues[index];
            }

            return kvalue;
        },

        /* 获取元素键值对 */
        getKeyValueItem: function (index) {
            var keyvalueItem = {};
            if (index > -1) {
                keyvalueItem.key = this.arrKeys[index];
                keyvalueItem.value = this.arrValues[index];
            }

            return keyvalueItem;
        },

        /* 清理所有元素 */
        clear: function () {
            if (this.count != 0) {
                this.arrKeys.splice(0, this.count);
                this.arrValues.splice(0, this.count);
                this.count = 0;
            }
        },

        /* 检测是否包含key */
        containKey: function (key) {
            var isContain = false;

            if (this._getElementIndex(key) > -1) {
                isContain = true;
            }

            return isContain;
        },

        /* 获取元素索引序号 */
        _getElementIndex: function (key) {
            var index = -1;

            var i;
            for (i = 0; i < this.arrKeys.length; i++) {
                if (this.arrKeys[i] == key) {
                    index = i;
                    break;
                }
            }

            return index;
        }
    };
    datastruct.dictionary.fn.init.prototype = datastruct.dictionary.fn;
    /*-------------------------------*/

    /* 
    -----数据结构转换类----- 
    */
    datastruct.convertion = {

        /* string转化为object */
        strToObject: function (str) {
            var jsonObj;

            /* json的字符串数据 */
            if (str.indexOf("{") > -1 || str.indexOf("[") > -1) {
                eval("jsonObj = " + str + ";");

                /* 数据字典 */
                if (jsonObj.struct && jsonObj.struct == "dictionary") {
                    var dict = new datastruct.dictionary();
                    for (var i = 0; i < jsonObj.items.length; i++) {
                        var itemObj = jsonObj.items[i];
                        dict.setItem(itemObj.key, itemObj.value);
                    }

                    jsonObj = dict;
                }
            }
            else {
                jsonObj = str;
            }

            return jsonObj;
        },

        /* 用js对象来填充业务对象 */
        fillToBizObj: function (obj, bizObj) {
            for (var prop in bizObj) {
                if (obj[prop]) {
                    bizObj[prop] = obj[prop];
                }
            }
        },

        /* object转化为string */
        objectToStr: function (obj) {
            var retStr = "";
            var ret = [];

            //不支持函数类型
            if (typeof (obj) == "function") {
                return;
            }

            //数组转换
            if (obj instanceof Array) {
                for (var i = 0, len = obj.length; i < len; i++) {
                    if (obj[i]) {
                        ret.push(datastruct.convertion.objectToStr(obj[i]));
                    }
                }

                retStr = "[" + ret.join(",") + "]";
            }
            //数据字典dictionary转换
            else if (obj instanceof datastruct.dictionary.fn.init) {
                for (var i = 0; i < obj.count; i++) {

                    var keyvalueItem = obj.getKeyValueItem(i);

                    ret.push("{ key: '" + keyvalueItem.key + "', value: " + datastruct.convertion.objectToStr(keyvalueItem.value) + " }");
                }

                retStr = "{ struct: 'dictionary', items: [" + ret.join(",") + "] }";
            }
            //值类型转换
            else if (typeof (obj) != "object") {
                if (obj.indexOf("'") > -1) {
                    retStr = "\"" + obj + "\"";
                }
                else {
                    retStr = "'" + obj + "'";
                }
            }
            //对象转换
            else {
                for (var item in obj) {
                    var m_value = obj[item];
                    if (m_value) {
                        ret.push(item + ":" + datastruct.convertion.objectToStr(m_value));
                    }
                }
                retStr = "{" + ret.join(",") + "}"; ;
            }

            return retStr;
        },

        /* string转化为html */
        strToHtml: function (str) {
            str = str.replace(/\n/g, "<br/>");
            str = str.replace(/\r/g, "");
            str = str.replace(/\s/g, "&nbsp;");

            return str;
        },

        /* html转化为string */
        htmlToStr: function (html) {
            html = html.replace(/\<br\/\>/g, "\n");
            html = html.replace(/&nbsp;/g, " ");

            return html;
        }
    }
    /*-------------------------------*/

})(window);


(function (window) {

    window.cachestore = {};

    /* 
    -----缓存处理辅助类----- 
    */
    cachestore.clientCacheHelper = {

        /* 缓存存储结构 */
        _cacheStorage: new window.datastruct.dictionary(),

        /* 添加或修改缓存元素 */
        setItem: function (cacheName, cacheStruct, param) {
            if (cacheStruct == cachestore.cacheStructEnum.value) {
                this._cacheStorage.setItem(cacheName, param);
            }
            else {
                var valueDict;
                if (!this._cacheStorage.containKey(cacheName)) {
                    valueDict = new window.datastruct.dictionary();
                    this._cacheStorage.setItem(cacheName, valueDict);
                }
                else {
                    valueDict = this._cacheStorage.getItem(cacheName);
                }

                valueDict.setItem(param.key, param.value);
            }
        },

        /* 删除缓存数据类 */
        removeCache: function (cacheName) {
            this._cacheStorage.removeItem(cacheName);
        },

        /* 删除缓存数据条目（只支持数据字典结构） */
        removeCacheItem: function (cacheName, paramKey) {
            if (!this._cacheStorage.containKey(cacheName)) {
                return;
            }

            this._cacheStorage.getItem(cacheName).removeItem(paramKey);
        },

        /* 获取缓存元素 */
        getItem: function (cacheName, key) {
            if (!this._cacheStorage.containKey(cacheName)) {
                return;
            }

            var cacheObj = this._cacheStorage.getItem(cacheName);

            var itemValue = "";
            if (cacheObj instanceof window.datastruct.dictionary.fn.init) {
                itemValue = cacheObj.getItem(key);
            }
            else {
                itemValue = cacheObj;
            }

            return itemValue;
        },

        /* 获取元素从Cookie中 */
        getItemFromCookie: function (name) {
            if (!document.cookie) {
                return;
            }

            var valueObj;
            var arrCookies = document.cookie.split(";");
            for (var i = 0; i < arrCookies.length; i++) {

                var cookieItem = arrCookies[i];
                var arrObjs = cookieItem.split("=");

                /* 缓存对象名称在Cookie中存在 */
                if ($.trim(arrObjs[0]) == name) {
                    valueObj = datastruct.convertion.strToObject(unescape(arrObjs[1]));
                }
            }
            return valueObj;
        },

        /* 从Cookie中移除元素 */
        removeItemInCookie: function (name) {
            var exp = new Date();
            exp.setTime(exp.getTime() - 1);
            var cval = this.getItemFromCookie(name);
            if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
        },

        /* 清除所有缓存 */
        clearCache: function () {
            this._cacheStorage.clear();
        },

        /* 读取缓存数据 */
        readCacheData: function (cacheName) {
            if (!document.cookie) {
                return;
            }

            var arrCookies = document.cookie.split(";");
            for (var i = 0; i < arrCookies.length; i++) {

                var cookieItem = arrCookies[i];
                var arrObjs = cookieItem.split("=");

                /* 缓存对象名称在Cookie中存在 */
                if ($.trim(arrObjs[0]) == cacheName) {

                    var valueObj = datastruct.convertion.strToObject(unescape(arrObjs[1]));

                    this._cacheStorage.setItem(cacheName, valueObj);

                    break;
                }
            }
        },

        /* 存储缓存数据 */
        saveToLocalStorage: function (cacheName, timelimit) {
            for (var i = 0; i < this._cacheStorage.count; i++) {
                var keyvalueItem = this._cacheStorage.getKeyValueItem(i);

                if (!cacheName || cacheName == keyvalueItem.key) {

                    var expireStr = "";
                    if (timelimit) {
                        var exp = new Date();
                        exp.setTime(exp.getTime() + 30 * 24 * 60 * 60 * 1000);
                        expireStr = "expires=" + exp.toGMTString();
                    }

                    document.cookie = keyvalueItem.key + "=" + escape(datastruct.convertion.objectToStr(keyvalueItem.value)) + ";path=/;" + expireStr;
                }
            }
        }
    };
    /*-------------------------------*/

    /* 
    -----缓存结构枚举----- 
    */
    cachestore.cacheStructEnum = {
        dictionary: 1,
        value: 2
    };
    /*-------------------------------*/

})(window);


(function (window) {

    window.runtime = {};

    /* 
    -----运行时设置参数----- 
    */
    window.runtime.clientRunSetting = {

        language: "language",

        /* 设置运行参数 */
        setRunParam: function (param, pvalue) {
            var obj = { key: param, value: pvalue };
            cachestore.clientCacheHelper.setItem("RunSetting", cachestore.cacheStructEnum.dictionary, obj);

            cachestore.clientCacheHelper.saveToLocalStorage("RunSetting", true);
        },

        /* 获取运行参数 */
        getRunParam: function (param) {
            var pvalue = cachestore.clientCacheHelper.getItem("RunSetting", param);

            if (!pvalue) {
                cachestore.clientCacheHelper.readCacheData("RunSetting");
            }
            pvalue = cachestore.clientCacheHelper.getItem("RunSetting", param);
            return pvalue;
        }
    }
    /*-------------------------------*/

})(window);


(function (window) {

    window.webhandler = {};

    /* 
    -----JavaScript和服务器的数据传输协议----- 
    */
    webhandler.webTransferObj = function (action, bizObj) {
        var obj = new webhandler.webTransferObj.fn.init(action, bizObj);
        return obj;
    };
    webhandler.webTransferObj.fn = {

        /* 构造函数 */
        init: function (action, bizObj) {
            this.Action = action;

            if (bizObj) {
                this.BizObj = datastruct.convertion.objectToStr(bizObj);
            }
        }
    };
    /*-------------------------------*/

    /* 
    -----业务执行环境----- 
    */
    webhandler.bizExeContext = function (successEvent, errorEvent) {
        var obj = new webhandler.bizExeContext.fn.init(successEvent, errorEvent);
        return obj;
    };
    webhandler.bizExeContext.fn = {

        /* 构造函数 */
        init: function (successEvent, errorEvent) {
            this.successEvent = successEvent;
            this.errorEvent = errorEvent;
        }
    };
    /*-------------------------------*/

    /* 
    -----ajax请求处理类----- 
    */
    webhandler.ajaxHandler = {

        /* 统一请求的Web处理程序 */
        _handlerUrl: null,

        /* 发送请求前的事件 */
        _beforeSendEvent: null,

        /* 异常处理事件 */
        _errorEvent: null,

        /* 请求处理完成事件 */
        _completeEvent: null,

        /* 初始化请求事件 */
        init: function (handlerUrl, beforeSendEvent, errorEvent, completeEvent) {
            this._handlerUrl = handlerUrl;
            this._beforeSendEvent = beforeSendEvent;
            this._errorEvent = errorEvent;
            this._completeEvent = completeEvent;
        },

        /* 业务请求 */
        bizRequest: function (transferObj, bizExeContext) {

            var param = datastruct.convertion.objectToStr(transferObj);

            $.ajax({
                url: this._handlerUrl,
                type: "post",
                async: true,
                cache: false,
                data: { Param: param },
                beforeSend: this._beforeSendEvent,
                error: this._errorEvent,
                complete: this._completeEvent,
                success: function (data, textStates) {

                    var retObj = datastruct.convertion.strToObject(data);

                    /* 异常标志Error */
                    if (retObj.Error) {
                        if (bizExeContext.errorEvent) {
                            bizExeContext.errorEvent(retObj);
                        }
                        else {
                            if (webhandler.ajaxHandler._errorEvent) {
                                webhandler.ajaxHandler._errorEvent(retObj);
                            }
                        }
                    }
                    else {
                        if (bizExeContext.successEvent) {
                            bizExeContext.successEvent(retObj);
                        }
                    }
                }
            });
        },

        /* 动态加载Javascript脚本 */
        loadScript: function (jsfile, successEvent) {
            $.ajax({
                url: jsfile,
                dataType: "script",
                cache: true,
                success: successEvent
            });
        },

        /* 上传文件 */
        uploadFile: function (fileForm, bizExeContext) {

            /* 发送前事件 */
            if (this._beforeSendEvent) {
                this._beforeSendEvent();
            }

            fileForm.submit();

            var responseStr = cachestore.clientCacheHelper.getItemFromCookie("Response");
            cachestore.clientCacheHelper.removeItemInCookie("Response");

            var retObj = datastruct.convertion.strToObject(responseStr);
            /* 异常标志Error */
            if (retObj.Error) {
                if (bizExeContext.errorEvent) {
                    bizExeContext.errorEvent(retObj);
                }
                else {
                    if (webhandler.ajaxHandler._errorEvent) {
                        webhandler.ajaxHandler._errorEvent(retObj);
                    }
                }
            }
            else {
                if (bizExeContext.successEvent) {
                    bizExeContext.successEvent(retObj);
                }
            }

            /* 成功处理后事件 */
            if (this._completeEvent) {
                this._completeEvent();
            }
        }
    }
    /*-------------------------------*/

})(window);

(function (window) {

    window.uicontrol = {};

    /* 
    -----通用控件函数----- 
    */
    uicontrol.func = {

    };
    /*-------------------------------*/

    /* 
    -----对话框控件----- 
    */
    uicontrol.dialog = function (ctrlId, title, layout, submitFunc) {
        var obj = new uicontrol.dialog.fn.init(ctrlId, title, layout, submitFunc);
        return obj;
    };
    uicontrol.dialog.fn = {
        /* 初始化函数 */
        init: function (ctrlId, title, layout, submitFunc) {

            var m_buttons = {};
            if (submitFunc) {
                m_buttons[mlm.C0024] = submitFunc;
                m_buttons[mlm.C0023] = function () { m_ctrl.dialog("close"); };
            }

            var m_ctrl = $("#" + ctrlId).dialog({
                resizable: false,
                height: layout.height,
                width: layout.width,
                title: title,
                modal: true,
                autoOpen: false,
                closeOnEscape: false,
                buttons: m_buttons
            });


            this.ctrl = m_ctrl;
        },

        /* 打开对话框 */
        show: function () {
            this.ctrl.dialog("open");
        }
    }
    uicontrol.dialog.fn.init.prototype = uicontrol.dialog.fn;
    /*-------------------------------*/

    /* 
    -----数据表格控件----- 
    */
    uicontrol.tableList = function (ctrlId, paramObj) {
        var obj = new uicontrol.tableList.fn.init(ctrlId, paramObj);
        return obj;
    };
    uicontrol.tableList.fn = {

        /* 初始化函数 */
        init: function (ctrlId, paramObj) {

            /* 是否支持分页 */
            if (!paramObj.isPaging) {
                paramObj.height = paramObj.height + 30;
            }

            this.keyColumn = paramObj.keyColumn;
            this.columns = paramObj.columns;

            this.dataGrid = $("#" + ctrlId).flexigrid({
                colModel: paramObj.columns,
                usepager: paramObj.isPaging,
                width: paramObj.width,
                height: paramObj.height,
                singleSelect: true, //仅允许选择单行
                resizable: false,
                striped: true,
                useRp: false,
                dataType: "json"
            });
        },

        /* 绑定数据源 */
        bindDataSource: function (source) {

            if (!source) {
                this.dataGrid.flexAddData({ page: 1, total: 0, rows: null });
                return;
            }

            var thisObj = this;

            var m_dataSource = new datastruct.dictionary();
            $.each(source.Rows, function () {

                var rowItem = this;
                var m_keyvalue;
                var itemObj = {};
                $.each(source.TableColumns, function (i, column) {
                    itemObj[column] = rowItem[i];

                    if (column == thisObj.keyColumn) {
                        m_keyvalue = rowItem[i];
                    }
                });

                m_dataSource.setItem(m_keyvalue, itemObj);
            });

            var m_bindSource = { page: 1, total: source.TotalCount, rows: [] };
            $.each(m_dataSource.arrValues, function (i, rowItem) {
                var m_key = m_dataSource.arrKeys[i];
                var m_rowObj = { id: m_key, cell: [] };

                /* 循环列 */
                $.each(thisObj.columns, function () {
                    /* 判断列是否需要调整 */
                    if (!this.adjust) {
                        m_rowObj.cell.push(rowItem[this.name]);
                    }
                    else {
                        var m_cellvalue = [];
                        /* 修改列构造函数 */
                        if (this.modifiedFunc) {
                            m_cellvalue.push("<a href='javascript:void(\"0\")' class='bt-link' tag='" + m_key + "' onclick='" + this.modifiedFunc + ".call(this);'>修改</a>");
                        }
                        /* 删除列构造函数 */
                        if (this.deletedFunc) {
                            m_cellvalue.push("<a href='javascript:void(\"0\")' class='bt-link' tag='" + m_key + "' onclick='" + this.deletedFunc + ".call(this);'>删除</a>");
                        }
                        /* 自定义列构造函数 */
                        if (this.createCell) {
                            m_cellvalue.push(this.createCell(m_key, rowItem[this.name]));
                        }

                        m_rowObj.cell.push(m_cellvalue.join(""));
                    }
                });

                m_bindSource.rows.push(m_rowObj);
            });

            this.dataGrid.flexAddData(m_bindSource);
        },

        /* 重新设置大小 */
        resize: function (height) {
            this.dataGrid[0].grid.bDiv.style.height = height + 'px';
            this.dataGrid[0].p.height = height;
            this.dataGrid[0].grid.fixHeight(height);
        }
    };
    uicontrol.tableList.fn.init.prototype = uicontrol.tableList.fn;
    /*-------------------------------*/

    /* 
    -----文件上传控件----- 
    */
    uicontrol.file = function (ctrlId) {
        var obj = new uicontrol.file.fn.init(ctrlId);
        return obj;
    };
    uicontrol.file.fn = {

        /* 构造函数 */
        init: function (ctrlId) {

            this.ctrlId = ctrlId;

            var formId = 'fileform_' + ctrlId;
            var frameId = 'fileframe' + ctrlId;

            this.fileForm = $("#" + formId);
            if (this.fileForm.length == 0) {
                this.fileForm = $('<form action="" method="post" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
                this.fileForm.css('position', 'absolute');
                this.fileForm.css('top', '-1200px');
                this.fileForm.css('left', '-1200px');
                this.fileForm.appendTo('body');
                this.paramCtrl = $('<input type="hidden" name="Param" />');
                this.paramCtrl.appendTo(this.fileForm);

                var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
                if ($.browser.msie) {
                    iframeHtml += " src=\"javascript:false\"";
                }
                iframeHtml += ' />';
                this.iframe = $(iframeHtml);
                this.iframe.appendTo(document.body);

                this.fileForm.attr('target', frameId);
                this.fileForm.attr('method', 'POST');
            }
        },

        /* 上传文件 */
        uploadFile: function (transferObj, bizExeContext) {
            var fileCtrl = $('#' + this.ctrlId);
            fileCtrl.before(fileCtrl.clone());

            var fileId = 'filectrl_' + this.ctrlId;
            this.fileForm.find("#" + fileId).remove();

            fileCtrl.attr('id', fileId);
            fileCtrl.appendTo(this.fileForm);

            //设置上传Url
            this.fileForm.attr('action', webhandler.ajaxHandler._handlerUrl + "?filename=" + this.ctrlId);

            //设置参数
            var paramObj = {};
            for (var item in transferObj) {
                paramObj[item] = transferObj[item];
            }
            var paramStr = datastruct.convertion.objectToStr(paramObj);

            this.paramCtrl.val(paramStr);

            /* 提交 */
            webhandler.ajaxHandler.uploadFile(this.fileForm, bizExeContext);
        }
    };
    uicontrol.file.fn.init.prototype = uicontrol.file.fn;
    /*-------------------------------*/

})(window);